package com.zhou.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import com.zhou.blog.dao.dos.Archives;
import com.zhou.blog.dao.mapper.*;
import com.zhou.blog.dao.pojo.*;
import com.zhou.blog.service.*;
import com.zhou.blog.utils.DateUtils;
import com.zhou.blog.utils.UserThreadLocal;
import com.zhou.blog.vo.*;
import com.zhou.blog.vo.params.ArticleParam;
import com.zhou.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @title:ArticleService
 * @Author Zhou
 * @Date:2022/4/12 22:47
 * @Version 1.0
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private TagService tagService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleBodyService articleBodyService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ThreadService threadService;
    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private ArticleBodyMapper articleBodyMapper;

//    @Override
//    public Result listArticle(PageParams pageParams) {
//        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
//        IPage<Article> articleIPage = this.articleMapper.listArticle(page,pageParams.getCategoryId(),pageParams.getTagId(),pageParams.getYear(),pageParams.getMonth());
//        return Result.success(copyList(articleIPage.getRecords(),true,true));
//    }

    @Override
    public Result listArticle(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();

        //order by create_date desc,是否置顶
        queryWrapper.orderByDesc(Article::getCreateDate,Article::getWeight);
        if (pageParams.getCategoryId() != null) {
            queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
        }

        if (pageParams.getTagId() != null){
            List<Long> articleIdList = new ArrayList<>();
            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
            for (ArticleTag articleTag : articleTags) {
                articleIdList.add(articleTag.getArticleId());
            }
            if (articleIdList.size() > 0){
                queryWrapper.in(Article::getId,articleIdList);
            }
        }
        //文章归档
        String year = pageParams.getYear();
        String month = pageParams.getMonth();
        if (year != null && year.length() > 0 && month != null && month.length() > 0){
            Map<String, Long> date = DateUtils.date(year, month);
            queryWrapper.between(Article::getCreateDate,date.get("startDatesTime"),date.get("endDatesTime"));
        }


        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
        List<Article> records = articlePage.getRecords();

        //实体对象集合转换成前端展示的VO对象集合
        List<ArticleVo> articleVoList = copyList(records,true,true);
        return Result.success(articleVoList);
    }

    /**
     * 查询最热文章
     * @param limit
     * @return
     */
    @Override
    public Result hotArticle(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId,Article::getTitle);
        queryWrapper.last("limit "+ limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        List<ArticleVo> articleVoList = copyList(articles, false, false);

        return Result.success(articleVoList);
    }

    /**
     * 查询最新文章
     * @param limit
     * @return
     */
    @Override
    public Result newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate).select(Article::getId,Article::getTitle);
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        List<ArticleVo> articleVoList = copyList(articles, false, false);
        return Result.success(articleVoList);

    }

    /**
     * 文章归档
     * @return
     */
    @Override
    public Result listArchives() {
        List<Archives> archivesList = articleMapper.listArchives();

        return Result.success(archivesList);
    }

    @Override
    public Result findArticleById(Long id) {
        /*
        根据id查询文章信息
        根据bodyId和categoryId进行联表查询
         */
        Article article = articleMapper.selectById(id);
        ArticleVo articleVo = copy(article,true,true,true,true);
        /*
        查看文章后增加阅读数
        查到文章后应该返回数据，但此时写入数据更新阅读数，增加了写锁，阻塞了读的操作，性能降低
        因此把更新操作放到线程池中进行，不妨碍主线程执行
         */
        threadService.updateViewCount(articleMapper,article);

        return Result.success(articleVo);
    }

    /**
     * 发布文章
     * @param articleParam
     * @return
     */
    @Override
    public Result publish(ArticleParam articleParam) {
        //创建新文章
        Article article = new Article();
        article.setWeight(Article.Article_Common);
        article.setViewCounts(0);
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setCreateDate(System.currentTimeMillis());
        article.setCategoryId(Long.valueOf(articleParam.getCategory().getId()));
        //当前发布文章的用户
        SysUser sysUser = UserThreadLocal.get();
        article.setAuthorId(sysUser.getId());
        //插入后会自动将生成的主键ID set到实体类中
        articleMapper.insert(article);
        //文章的标签参数写入
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                Long articleId = article.getId();
                ArticleTag articleTag = new ArticleTag();
                articleTag.setTagId(Long.valueOf(tag.getId()));
                articleTag.setArticleId(articleId);
                articleTagMapper.insert(articleTag);
            }
        }
        //文章内容存到articleBody
        ArticleBody articleBody = new ArticleBody();
        articleBody.setArticleId(article.getId());
        //从参数获取articleBody内容
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        //插入数据库后生成主键ID并自动set到实体类中
        articleBodyMapper.insert(articleBody);
        //将articleBody参数写入article
        article.setBodyId(articleBody.getId());
        //articleBody参数写入article后更新数据库
        articleMapper.updateById(article);
        Map<String,String> map = new HashMap<>();
        map.put("id",article.getId().toString());
        return Result.success(map);
    }

    //实体对象集合转换成前端展示的VO对象集合的实现方法
    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,false,false));
        }
        return articleVoList;
    }

    private List<ArticleVo> copyList(List<Article> records,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record,isTag,isAuthor,isBody,isCategory));
        }
        return articleVoList;
    }

    //将实体类转换成前端展示的VO对象的实现方法
    private ArticleVo copy(Article article,boolean isTag,boolean isAuthor,boolean isBody,boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);

        articleVo.setId(String.valueOf(article.getId()));
        //数据库里的Long型时间戳转换成前端展示的String
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //部分接口不需要标签及作者数据
        if (isTag) {
            //通过文章id查询标签并赋值给vo对象
            articleVo.setTags(tagService.findTagsByArticleId(article.getAuthorId()));
        }
        if(isAuthor){
            articleVo.setAuthor(sysUserService.findUserById(article.getAuthorId()).getNickname());
        }
        if (isBody) {
            Long bodyId = article.getBodyId();
            articleVo.setBody(findArticleBodyVoById(bodyId));
        }
        if (isCategory) {
            Long categoryId = article.getCategoryId();
            articleVo.setCategory(findCategoryVoById(categoryId));
        }
        return articleVo;
    }

    private CategoryVo findCategoryVoById(Long categoryId) {
        Category category = categoryService.findCategoryById(categoryId);
        CategoryVo categoryVo = new CategoryVo();
        BeanUtils.copyProperties(category,categoryVo);
        return categoryVo;
    }


    private ArticleBodyVo findArticleBodyVoById(Long bodyId) {
        ArticleBody articleBody = articleBodyService.findArticleBodyById(bodyId);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
